package librarymanager



import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
import grails.plugin.springsecurity.annotation.Secured
import authentication.Role

@Transactional(readOnly = true)
@Secured(['ROLE_ADMIN','ROLE_MANAGER','ROLE_PROFESSOR','ROLE_STUDENT'])
class BookController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def springSecurityService
    
    def index() {
        def result
        if (params.searchButton) {
            result = Book.executeQuery("from Book b \
                where b.title like :title and b.category in (:categs)",        
                [title: "%${params.title}%", categs: getCategories()])
        } else {                        
            result = Book.executeQuery("from Book b \
                where b.category in (:categs)",
                [categs: getCategories()])
        }
        respond result, model:[bookInstanceCount: result.size()]
    }
    
    def insecure() {
        def result
        def ids        
        if (params.searchButton) {            
            ids = getCategoriesIds();
            result = Book.executeQuery("from Book b \
                where b.title like '%${params.title}%' \
                    and b.category.id in (${ids}) \
                    order by b.title asc")            
        } else {
            ids = getCategoriesIds();
            result = Book.executeQuery("from Book b \
                where b.category.id in (${ids}) \
                order by b.title asc")
        }
        respond result, model:[bookInstanceCount: result.size()]
    }
    
    private ArrayList<Category> getCategories() {
        def authority = springSecurityService.principal.authorities[0]
        Role role = Role.findByAuthority("${authority}")
        def categories = Category.list()
        def categs = new ArrayList<>()
        for (def c in categories) {
            if (c.roles.contains(role)) {
                categs.add(c)
            }
        }
        return categs
    }
    private String getCategoriesIds() {
        def authority = springSecurityService.principal.authorities[0]
        Role role = Role.findByAuthority("${authority}")
        def categories = Category.list()
        def categs = new ArrayList<>()
        for (def c in categories) {
            if (c.roles.contains(role)) {
                categs.add(c.id)
            }
        }
        String ret = categs.toString()
        ret = ret.substring(1, ret.length() - 1)
        return ret        
    }
    
    def show(Book bookInstance) {
        respond bookInstance
    }

    @Secured(['ROLE_ADMIN','ROLE_MANAGER'])
    def create() {
        respond new Book(params)
    }

    @Transactional
    @Secured(['ROLE_ADMIN','ROLE_MANAGER'])
    def save(Book bookInstance) {
        if (bookInstance == null) {
            notFound()
            return
        }

        if (bookInstance.hasErrors()) {
            respond bookInstance.errors, view:'create'
            return
        }

        bookInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'book.label', default: 'Book'), bookInstance.id])
                redirect bookInstance
            }
            '*' { respond bookInstance, [status: CREATED] }
        }
    }

    @Secured(['ROLE_ADMIN','ROLE_MANAGER'])
    def edit(Book bookInstance) {
        respond bookInstance
    }

    @Transactional
    @Secured(['ROLE_ADMIN','ROLE_MANAGER'])
    def update(Book bookInstance) {
        if (bookInstance == null) {
            notFound()
            return
        }

        if (bookInstance.hasErrors()) {
            respond bookInstance.errors, view:'edit'
            return
        }

        bookInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'Book.label', default: 'Book'), bookInstance.id])
                redirect bookInstance
            }
            '*'{ respond bookInstance, [status: OK] }
        }
    }

    @Transactional
    @Secured(['ROLE_ADMIN','ROLE_MANAGER'])
    def delete(Book bookInstance) {

        if (bookInstance == null) {
            notFound()
            return
        }

        bookInstance.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'Book.label', default: 'Book'), bookInstance.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }   
}
